import ProFromTabsList from '@/components/ProFromTabsList';
import TagList from '@/components/TagList';
import { UpCircleOutlined } from '@ant-design/icons';
import {
  ModalForm,
  ProCard,
  ProForm,
  ProFormDependency,
  ProFormDigit,
  ProFormDigitRange,
  ProFormGroup,
  ProFormList,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-components';
import { request } from '@umijs/max';
import { Col, Flex, Form, message, Modal, Space, Tooltip, Typography } from 'antd';
import { flatten, isUndefined, map, uniq } from 'lodash';
import React, { FC } from 'react';

type GithubIssueItem = {
  id: number;
  appName: string;
  endRange: number;
  tasks: Record<string, any>[];
};

interface IndexProps {
  trigger: React.ReactElement;
  initialValue?: GithubIssueItem;
  reload: () => void;
}

const codeOptions = [
  { label: '点击目标', value: 5 },
  { label: '点击范围', value: 6 },
  { label: '点击模糊文字', value: 16 },
  { label: '点击规则文字', value: 17 },
  { label: '点击精确描述', value: 18 },
  { label: '点击模糊描述', value: 19 },
  { label: '点击规则描述', value: 20 },
  { label: '检测关键字', value: 11 },
  { label: '点击同行的文字', value: 12 },
  { label: '下滑', value: 7 },
  { label: '上滑', value: 8 },
  { label: '小下滑', value: 9 },
  { label: '小上滑', value: 10 },
  { label: '左向右滑动', value: 14 },
  { label: '右向左滑动', value: 15 },
  { label: '点击范围', value: 6 },
  { label: '关闭广告', value: 13 },
  { label: '退出', value: -1 },
  { label: '复位', value: 1 },
  { label: '后退', value: 2 },
  { label: '选择应用', value: 3 },
  { label: '打开应用', value: 4 },
];

const Index: FC<IndexProps> = ({ initialValue, trigger, reload }) => {
  const [form] = Form.useForm<GithubIssueItem>();

  const digitRangeValidator = (rules: any, value: number[]) => {
    if (rules.required && value.some((item) => isUndefined(item))) {
      return Promise.reject(new Error('请选择范围'));
    }
    if (rules.required && value?.[0] > value?.[1]) {
      return Promise.reject(new Error('结束时间不能小于开始时间'));
    }
    return Promise.resolve();
  };

  return (
    <ModalForm<GithubIssueItem>
      width="90%"
      title="新建/编辑"
      trigger={trigger}
      form={form}
      layout="horizontal"
      grid
      onOpenChange={(isOpen) => isOpen && initialValue && form.setFieldsValue(initialValue)}
      rowProps={{ gutter: [16, 0] }}
      modalProps={{
        style: { top: 24 },
        destroyOnClose: true,
      }}
      preserve={false}
      submitTimeout={2000}
      onFinish={async (values) => {
        console.log(values);
        await request('/api/config', { method: 'post', data: values });
        message.success(values.id ? '编辑成功' : '创建成功');
        reload();
        return true;
      }}
      scrollToFirstError={true}
      onFinishFailed={(errorInfo) => {
        console.log(errorInfo);
        Modal.error({
          width: 500,
          content: (
            <Flex vertical gap={8}>
              <Typography.Text>
                有<Typography.Text type="danger">{errorInfo.errorFields?.length}</Typography.Text>
                个,错误项
              </Typography.Text>

              {errorInfo.errorFields?.map((item, index) => (
                <Typography.Text key={index}>
                  <code>{item.name.join(' > ')}</code>：
                  <Typography.Text type="danger">{item.errors.join('-')}</Typography.Text>
                </Typography.Text>
              ))}
            </Flex>
          ),
        });
      }}
    >
      <ProFormText name="id" hidden />

      <ProFormText
        name="appName"
        label="应用名称"
        placeholder="请输入"
        rules={[{ required: true }]}
        colProps={{ md: 6, xl: 6 }}
      />

      <ProFormText
        name="groupName"
        label="组名称"
        placeholder="请输入"
        rules={[{ required: true }]}
        colProps={{ md: 6, xl: 6 }}
      />

      <ProFormDigit
        initialValue={0}
        name="seq"
        label="顺序"
        placeholder="请输入"
        min={0}
        max={9}
        rules={[{ required: true }]}
        colProps={{ md: 6, xl: 6 }}
      />

      <ProFormDigit
        initialValue={1}
        name="execTimes"
        label="总执行次数"
        placeholder="请输入"
        min={1}
        max={99}
        rules={[{ required: true }]}
        colProps={{ md: 6, xl: 6 }}
      />

      <ProFormDigitRange
        name="endRange"
        label="时间范围"
        rules={[{ required: true, validator: digitRangeValidator }]}
        colProps={{ md: 8, xl: 8 }}
        help="单位：分钟"
      />

      <ProForm.Item name="unmatch" label="未知处理关键字">
        <TagList />
      </ProForm.Item>

      <ProFormList
        name="tasks"
        label="任务集"
        rules={[
          {
            required: true,
            validator(rule, value) {
              if (!value || value?.length === 0) {
                return Promise.reject(new Error('至少添加一个任务'));
              }
              return Promise.resolve();
            },
          },
        ]}
        actionRender={(field, action, defaultActionDom) => [
          defaultActionDom,
          field.name !== 0 && (
            <Tooltip placement="top" title="上移一行">
              <UpCircleOutlined
                style={{ marginLeft: 12 }}
                onClick={() => {
                  action.move(field.name, field.name - 1);
                }}
              />
            </Tooltip>
          ),
        ]}
      >
        <ProFormGroup key="group">
          <ProFormText rules={[{ required: true }]} colProps={{ md: 8, xl: 8 }} name="name" placeholder="请输入名称" />
          <ProFormSelect
            colProps={{ md: 8, xl: 8 }}
            rules={[{ required: true }]}
            name="type"
            options={[
              { label: '时间', value: 0 },
              { label: '次数', value: 1 },
            ]}
            placeholder="请选择类型"
          />
          <ProFormDependency key="timeRange" name={['type']}>
            {({ type }) => {
              return type === 1 ? (
                <ProFormDigit
                  rules={[{ required: true }]}
                  colProps={{ md: 8, xl: 8 }}
                  name="times"
                  placeholder="请输入次数"
                />
              ) : (
                <ProFormDigitRange
                  rules={[{ required: true }]}
                  colProps={{ md: 8, xl: 8 }}
                  name="timeRange"
                  placeholder="时间范围"
                />
              );
            }}
          </ProFormDependency>
        </ProFormGroup>
      </ProFormList>
      <ProForm.Item noStyle name="pages">
        <ProFromTabsList>
          <ProFormGroup>
            <ProFormText colProps={{ md: 12, xl: 12 }} name="name" label="名称" rules={[{ required: true }]} />

            <Form.Item name="keywords" label="关键字" rules={[{ required: true }]}>
              <TagList />
            </Form.Item>
          </ProFormGroup>

          <ProFormList
            style={{ marginBlockEnd: 0 }}
            name="conditions"
            copyIconProps={{ tooltipText: '复制此项到末尾' }}
            deleteIconProps={{ tooltipText: '删除此条件' }}
            actionRender={(field, action, defaultActionDom) => [
              defaultActionDom,
              field.name !== 0 && (
                <Tooltip placement="top" title="上移一行">
                  <UpCircleOutlined
                    style={{ marginLeft: 12 }}
                    onClick={() => {
                      action.move(field.name, field.name - 1);
                    }}
                  />
                </Tooltip>
              ),
            ]}
            itemRender={({ listDom, action }, { record }) => {
              return (
                <ProCard
                  collapsible
                  defaultCollapsed
                  size="small"
                  bordered
                  title={
                    <Space>
                      <Typography.Text>执行条件</Typography.Text>
                      <Typography.Text type="success">{record.state}</Typography.Text>
                    </Space>
                  }
                  extra={action}
                  style={{ marginBlockEnd: 8 }}
                >
                  {listDom}
                </ProCard>
              );
            }}
            creatorButtonProps={{ creatorButtonText: '添加条件' }}
            initialValue={[]}
          >
            <ProFormGroup>
              <ProFormText colProps={{ md: 8, xl: 8 }} name="state" label="状态" rules={[{ required: true }]} />

              <ProFormDependency key="tasks" name={['tasks']} ignoreFormListField>
                {({ tasks }) => [
                  <ProFormSelect
                    key="task"
                    colProps={{ md: 8, xl: 8 }}
                    name="task"
                    label="执行任务"
                    params={{ tasks }}
                    request={async (params) =>
                      params.tasks?.map((i: Record<string, any>) => ({
                        label: i.name,
                        value: i.name,
                      }))
                    }
                  />,
                  <ProFormSelect
                    key="endTask"
                    colProps={{ md: 8, xl: 8 }}
                    name="endTask"
                    label="完成任务"
                    params={{ tasks }}
                    request={async (params) =>
                      params.tasks?.map((i: Record<string, any>) => ({
                        label: i.name,
                        value: i.name,
                      }))
                    }
                  />,
                ]}
              </ProFormDependency>
              <ProFormDependency key="pages" name={['pages', ['conditions', ['state']]]} ignoreFormListField>
                {({ pages }) => (
                  <ProFormSelect
                    mode="multiple"
                    colProps={{ md: 8, xl: 8 }}
                    name="stateRange"
                    label="状态匹配"
                    options={uniq(flatten(map(pages, (i) => map(i.conditions, (i) => i.state)))).map((i) => ({
                      label: i,
                      value: i,
                    }))}
                  />
                )}
              </ProFormDependency>
              <ProFormDigitRange
                colProps={{ md: 8, xl: 8 }}
                name="updateTimeRange"
                label="任务更新时间匹配"
                help="单位：秒"
                rules={[{ validator: digitRangeValidator }]}
              />
              <ProFormDigitRange
                colProps={{ md: 8, xl: 8 }}
                name="createTimeRange"
                label="任务创建时间匹配"
                help="单位：秒"
                rules={[{ validator: digitRangeValidator }]}
              />
              <ProForm.Item name="keywords" label="关键字匹配">
                <TagList />
              </ProForm.Item>
            </ProFormGroup>

            <ProFormList
              style={{ marginBlockEnd: 0 }}
              name="cmds"
              initialValue={[{}]}
              copyIconProps={{ tooltipText: '复制此项到末尾' }}
              deleteIconProps={{ tooltipText: '删除此条件' }}
              creatorButtonProps={{ creatorButtonText: '添加命令' }}
              itemRender={({ listDom, action }, { record }) => {
                return (
                  <ProCard
                    collapsible
                    defaultCollapsed
                    size="small"
                    bordered
                    title={
                      <Space>
                        <Typography.Text>命令</Typography.Text>
                        <Typography.Text type="success">
                          {' '}
                          {codeOptions.find((i) => i.value === record.code)?.label}
                        </Typography.Text>
                      </Space>
                    }
                    extra={action}
                    style={{ marginBlockEnd: 8 }}
                  >
                    {listDom}
                  </ProCard>
                );
              }}
            >
              <ProFormGroup>
                <ProFormSelect
                  colProps={{ md: 12, xl: 12 }}
                  name="code"
                  label="值"
                  options={codeOptions}
                  rules={[{ required: true }]}
                />
                <Col md={12} xl={12}>
                  <ProForm.Item name="params" label="参数">
                    <TagList />
                  </ProForm.Item>
                </Col>
              </ProFormGroup>
            </ProFormList>
          </ProFormList>
        </ProFromTabsList>
      </ProForm.Item>
    </ModalForm>
  );
};

export default Index;
